package org.budo.criteria.parser;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author lmw
 */
@Getter
@Setter
@ToString
public class SqlUnitBuffer implements Serializable {
    private static final long serialVersionUID = -3665358372762733056L;

    private String sql;

    private Map<String, Object> parameters;

    public SqlUnitBuffer() {
        this.sql = "";
        this.parameters = new HashMap<String, Object>();
    }

    /**
     * 返回参数占位符
     */
    public String parameter(Object value) {
        String parameterKey = this.parameterKey();

        parameters.put(parameterKey, value);
        return "#{" + parameterKey + "}";
    }

    private String parameterKey() {
        for (int i = 0;; i++) {
            String key = "$" + i;
            boolean contains = parameters.containsKey(key);
            if (contains) {
                continue;
            }

            return key;
        }
    }

    public SqlUnitBuffer appendSql(String sql) {
        this.sql += sql;
        return this;
    }

    public void and(SqlUnitBuffer sqlUnitBuffer) {
        this.appendSql(" AND " + sqlUnitBuffer.getSql());
        this.parameters.putAll(sqlUnitBuffer.getParameters());
    }
}